import { CustomRequestConfig } from '../service'
import qs from 'qs'

// 存储请求和对应的取消函数
let pendingMap = new Map<string, AbortController>()

// 序列化参数
export const getPendingUrl = (config: CustomRequestConfig) =>
  [config.method, config.url, qs.stringify(config.data), qs.stringify(config.params)].join('&')

export class AxiosCancer {
  addPending(config: CustomRequestConfig) {
    this.removePending(config)

    const url = getPendingUrl(config)
    const controller = new AbortController()
    config.signal = controller.signal
    pendingMap.set(url, controller)
  }

  removePending(config: CustomRequestConfig) {
    const url = getPendingUrl(config)
    const controller = pendingMap.get(url)
    controller && controller.abort()
  }

  /**
   * @description: 清空所有pending
   */
  removeAllPending() {
    pendingMap.forEach((controller) => {
      controller && controller.abort()
    })
    pendingMap.clear()
  }
}
